<template>
  <div class="list-common-table">
    <t-form ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
            <t-col :span="4">
              <t-form-item :label="$t('components.goodsTable.goodsName')" name="name">
                <t-input
                  v-model="formData.name"
                  class="form-item-content"
                  type="search"
                  :placeholder="$t('请输入')"
                  :style="{ minWidth: '100px' }"
                />
              </t-form-item>
            </t-col>
            <!--<t-col :span="3">
              <t-form-item :label="$t('components.goodsTable.goodsStatus')" name="status">
                <t-select v-model="formData.status" class="form-item-content" :options="GOODS_STATUS_OPTIONS"
                  :placeholder="$t('请选择')" clearable />
              </t-form-item>
            </t-col>-->
            <t-col :span="4">
              <t-form-item :label="$t('components.goodsTable.goodsType')" name="type">
                <t-select
                  v-model="formData.type"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="CONTRACT_TYPE_OPTIONS"
                  :placeholder="$t('请选择')"
                  clearable
                />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }" @click="handleClickQuery">
            {{ $t('components.goodsTable.query') }}
          </t-button>
          <t-button type="reset" variant="base" theme="default"> {{ $t('components.commonTable.reset') }} </t-button>
          <t-button shape="circle" theme="danger" @click="toShop">
            <!--返回商品页的按钮-->
            <rollback-icon />
          </t-button>
        </t-col>
      </t-row>
    </t-form>

    <!--定义表格的内容，后端数据叫cartData，假数据叫fakeData-->

    <div class="table-container">
      <t-table
        :data="cartData"
        :columns="COLUMNS"
        :row-key="rowKey"
        :vertical-align="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="headerAffixedTop"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
      >
        <template #orderstatus="{ row }">
          <t-tag v-if="row.orderstatus === 3" theme="success" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.finish') }}
          </t-tag>
          <t-tag v-if="row.orderstatus === 0" theme="warning" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.unpaid') }}
          </t-tag>
          <t-tag v-if="row.orderstatus === 1" theme="primary" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.paid') }}
          </t-tag>
          <t-tag v-if="row.orderstatus === 2" theme="default" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.cancelled') }}
          </t-tag>
        </template>
        <!--下面的没用上-->
        <!--
        <template #contractType="{ row }">
          <p v-if="row.contractType === CONTRACT_TYPES.MAIN">普通商品</p>
          <p v-if="row.contractType === CONTRACT_TYPES.SUB">服务</p>
        </template>
        -->
        <!--
        <template #paymentType="{ row }">
          <div v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.PAYMENT" class="payment-col">
            {{ $t('pages.listBase.pay') }}
            <trend class="dashboard-item-trend" type="up" />
          </div>
          <div v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.RECEIPT" class="payment-col">
            {{ $t('pages.listBase.receive') }}
            <trend class="dashboard-item-trend" type="down" />
          </div>
        </template>-->
        <template #orderid="{ row }">
          <t-space>
            <t-link theme="primary" @click="handleClickBuy(row)"> 购买</t-link>
            <t-link theme="danger" @click="handleClickDelete"> 删除</t-link>
          </t-space>
          <!--确认购买对话框-->
          <dialog-form
            v-model:visible="formDialogVisible"
            :orderid="buyorderid"
            :number="buynumber"
            :goodid="buygoodid"
            :sTimeBegin="timeBegin"
            :sTimeEnd="timeEnd"
            :sTimeId="timeId"
            :buyType="buyType"
            :sAvailable="available"
          />
          <!--删除确认对话框-->
          <t-dialog
            v-model:visible="confirmVisible"
            header="亲亲，您确定要删除吗？"
            :body="confirmBody"
            :on-cancel="onCancel"
            @confirm="onConfirmDelete(row)"
          />
        </template>
      </t-table>
    </div>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios';
import { RollbackIcon } from 'tdesign-icons-vue-next';
import { DialogProps, MessagePlugin, PageInfo, PrimaryTableCol, TableRowData } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { getList } from '@/api/list';
import Trend from '@/components/trend/index.vue';
import { prefix } from '@/config/global';
import { CONTRACT_PAYMENT_TYPES, CONTRACT_STATUS, CONTRACT_TYPES, GOODS_STATUS, GOODS_TYPES } from '@/constants';
import { t } from '@/locales';
import { useSettingStore } from '@/store';

import DialogForm from './components/DialogForm.vue';
/*
const getConfirmBtn: DialogProps['confirmBtn'] = () => {
  return <t-button theme="outline">确认删除</t-button>;
};
const getCancelBtn: DialogProps['cancelBtn'] = () => {
  return <t-button theme="primary">再想想</t-button>;
}; */
interface FormData {
  name: string;
  no: string;
  status?: number;
  type: string;
}
// 假的数据，已弃用
/*
const fakeData = [
  {
    ordername: '鱼粮',
    orderstatus: '有货',
    orderamount: '100',
    number: '1',
  }, // 名称按照后端传入的数据定下
]; */

const toShop = () => {
  router.push('/shop/goods');
};
const store = useSettingStore();
const router = useRouter();

const GOODS_STATUS_OPTIONS = [
  { value: GOODS_STATUS.UNAVAILABLE, label: t('components.goodsTable.goodsStatusEnum.unavailable') },
  { value: GOODS_STATUS.AVAILABLE, label: t('components.goodsTable.goodsStatusEnum.available') },
];

const CONTRACT_TYPE_OPTIONS = [
  { value: GOODS_TYPES.ITEM, label: '一般商品' },
  { value: GOODS_TYPES.SERVICE, label: '服务' },
];
const COLUMNS: PrimaryTableCol[] = [
  {
    title: '商品名称',
    fixed: 'left',
    width: 280,
    ellipsis: true,
    align: 'left',
    colKey: 'ordername',
  },
  {
    title: '商品状态',
    width: 160,
    ellipsis: true,
    colKey: 'orderstatus',
  },
  {
    title: '总价/元',
    width: 160,
    ellipsis: true,
    colKey: 'orderamount',
  },
  {
    title: '数量',
    width: 160,
    ellipsis: true,
    colKey: 'number',
  },
  {
    align: 'left',
    fixed: 'right',
    width: 160,
    colKey: 'orderid', // 原来叫op
    title: t('components.goodsTable.operation'),
  },
];

const searchForm = {
  name: '',
  no: '',
  type: '',
};

const formData = ref<FormData>({ ...searchForm });
const rowKey = 'index';
const verticalAlign = 'top' as const;
const hover = true;

const handleClickQuery = async () => {
  try {
    cartData.value = [];
    const response = await axios.get('/api/user/getCart', {
      params: { name: formData.value.name, type: formData.value.type },
    });
    // 处理响应数据
    console.log(response.data);
    const list = response.data.data.list;
    cartData.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
    dataLoading.value = false;
  } catch (error) {
    // 处理请求错误
    console.error('Error fetching data:', error);
    // 可以选择显示一个错误消息给用户
    MessagePlugin.warning('没搜到任何东西呢！');
    // 隐藏加载指示器
    dataLoading.value = false;
  } finally {
    dataLoading.value = false;
  }
};

const pagination = ref({
  defaultPageSize: 20,
  total: 1,
  defaultCurrent: 1,
});
const confirmVisible = ref(false);
const data = ref([]);
const dataLoading = ref(false);
const cartData = ref([]);
const VIP = ref(false);

const fetchData = async () => {
  // console.log("fetchData")
  // dataLoading.value = true;
  try {
    // console.log("fetchData1")
    // 获取购物车数据
    const response = await axios.get('/api/user/getCart');
    // 获取用户数据
    const response1 = await axios.get('/api/user/getSelfInfo');
    // 从返回的响应中提取数据
    // data.value = list;
    const list = response.data.data.list;
    const isVIP = response1.data.data.isvip;
    console.log(list);
    console.log(isVIP);
    cartData.value = list;
    VIP.value = isVIP;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
    dataLoading.value = false;
  } catch (error) {
    // 处理请求错误
    console.error('Error fetching data:', error);
    // 可以选择显示一个错误消息给用户
    MessagePlugin.warning('小主，您的购物车空空如也哦！');
    // 隐藏加载指示器
    dataLoading.value = false;
  } finally {
    dataLoading.value = false;
  }
};

onMounted(() => {
  // 先获取购物车数据
  fetchData();
});
/*
const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { name } = data.value[deleteIdx.value];
    return `删除后，${name}的所有合同信息将被清空，且无法恢复`;
  }
  return '';
});
*/
const deleteIdx = ref(null);
const confirmBody = '删除后不可恢复哦！';

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = async (row) => {
  // 购物车删除
  try {
    // 将购物车中的条目删除
    const response = await axios.delete('/api/user/deleteCart', {
      params: {
        id: row.orderid, // 订单id
      },
    });
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    // 处理响应数据（如果需要）
    console.log(response.data);
  } catch (error) {
    // 处理请求错误
    console.error('删除失败:', error);
    // 可以选择显示一个错误消息给用户
    MessagePlugin.error('删除失败，请稍后再试。');
  }
};

const onCancel = () => {
  resetIdx();
};
// slot: { row: { orderid: number } }
const handleClickDelete = () => {
  // deleteIdx.value = slot.row.orderid;
  confirmVisible.value = true;
};
const onReset = (val: unknown) => {
  console.log(val);
};

/* const handleClickDetail = () => {
  router.push('/detail/base');
}; */
const formDialogVisible = ref(false);
const buygoodid = ref(null);
const buyorderid = ref(null);
const buynumber = ref(null);
const timeBegin = [];
const timeEnd = [];
const timeId = [];
const buyType = ref(null);
const available = [];
const handleClickBuy = async (row: { goodid: number; number: number; orderid: number }) => {
  formDialogVisible.value = true;
  buygoodid.value = row.goodid;
  buynumber.value = row.number;
  buyorderid.value = row.orderid;

  const response1 = await axios.get('/api/user/getServiceTime', {
    params: {
      id: row.goodid, // 商品id
    },
  });
  if (response1.data.data.list.length === 0) {
    buyType.value = 'item';
  } else {
    console.log(response1.data);
    buyType.value = 'service';
    let i = 0;
    for (i = 0; i < response1.data.data.list.length; i++) {
      timeBegin[i] = response1.data.data.list[i].date;
      timeEnd[i] = response1.data.data.list[i].time;
      timeId[i] = response1.data.data.list[i].id;
      available[i] = response1.data.data.list[i].available;
    }
  }
};

const onSubmit = (val: unknown) => {
  console.log(val);
  console.log(formData.value);
};
const rehandlePageChange = (pageInfo: PageInfo, newDataSource: TableRowData[]) => {
  console.log('分页变化', pageInfo, newDataSource);
};
const rehandleChange = (changeParams: unknown, triggerAndData: unknown) => {
  console.log('统一Change', changeParams, triggerAndData);
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}
</style>
